import os
import csv
from flask import Blueprint, render_template, jsonify
from fund.get_history_data import read_funds_from_yml_list
from my_const import MY_PREFER_FUND_YML_LIST, HISTORY_DIR

from util.log_util import get_the_logger
logger = get_the_logger(__name__)

latest_valuation_bp = Blueprint('latest_valuation', __name__)

def get_latest_valuation_data():
    """获取所有基金的最新估值数据"""
    try:
        # 获取所有基金代码和名称
        fund_code_list, code_to_name_map = read_funds_from_yml_list(MY_PREFER_FUND_YML_LIST)
        
        # 存储所有基金的最新估值数据
        latest_valuations = []
        
        # 遍历每个基金
        for fund_code in fund_code_list:
            try:
                # CSV文件路径
                csv_file_path = os.path.join(HISTORY_DIR, f"{fund_code}-daily.csv")
                
                # 检查文件是否存在
                if not os.path.exists(csv_file_path):
                    logger.warning(f"CSV文件不存在: {csv_file_path}")
                    continue
                
                # 读取CSV文件的最后一行数据
                with open(csv_file_path, 'r', encoding='utf-8-sig') as f:
                    reader = csv.reader(f)
                    
                    # 读取表头
                    header = next(reader, None)
                    if not header or header != ["净值日期", "单位净值", "日增长率"]:
                        logger.warning(f"CSV文件格式不正确: {csv_file_path}")
                        continue
                    
                    # 读取所有行并获取最后一行
                    rows = list(reader)
                    if not rows:
                        logger.warning(f"CSV文件无数据: {csv_file_path}")
                        continue
                    
                    # 获取最后一行数据
                    last_row = rows[-1]
                    if len(last_row) >= 3:
                        latest_valuations.append({
                            'fund_code': fund_code,
                            'fund_name': code_to_name_map.get(fund_code, '未知名称'),
                            'latest_date': last_row[0],
                            'latest_value': last_row[1],
                            'latest_growth': last_row[2]
                        })
            except Exception as e:
                logger.error(f"处理基金 {fund_code} 时出错: {str(e)}")
                continue
        
        return latest_valuations
    except Exception as e:
        logger.error(f"获取最新估值数据时出错: {str(e)}")
        return []


@latest_valuation_bp.route('/api/trigger-realtime-valuation', methods=['POST'])
def trigger_realtime_valuation():
    """手动触发基金实时估值任务"""
    try:
        # 直接调用实时数据获取函数（与定时任务执行相同逻辑）
        from web.scheduler import job_get_fund_realtime_data
        job_get_fund_realtime_data()
        return jsonify({
            "success": True,
            "message": "实时估值任务已启动并完成"
        })
    except Exception as e:
        # 捕获并返回错误信息
        return jsonify({
            "success": False,
            "error": f"实时估值任务执行失败：{str(e)}"
        }), 500


@latest_valuation_bp.route('/latest-valuation')
def latest_valuation_page():
    """最新估值展示页面"""
    # 获取最新估值数据
    latest_valuations = get_latest_valuation_data()
    logger.info(len(latest_valuations))
    
    return render_template('latest_valuation.html', latest_valuations=latest_valuations)


if __name__ == '__main__':
    print(get_latest_valuation_data())
    print(get_latest_valuation_data())